package com.eqdd.yiqidian.ui.gongneng.renshi.meeting

import android.app.Activity
import android.content.Intent
import android.support.v7.widget.RecyclerView
import android.view.View
import com.bigkoo.pickerview.TimePickerView
import com.eqdd.yiqidian.R
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector
import com.eqdd.yiqidian.base.Config
import com.eqdd.yiqidian.bean.DepartmentStaffTreeBean
import com.eqdd.yiqidian.bean.MeetingTypeInfoBean
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimEditEnterBean
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimEditHintBean
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimTimeSelectBean
import com.eqdd.yiqidian.http.DialogCallBack
import com.eqdd.yiqidian.http.HttpConfig
import com.eqdd.yiqidian.http.HttpResult
import com.eqdd.yiqidian.ui.base.SlimBaseMultiEditActivity
import com.eqdd.yiqidian.ui.tongxunlu.stafftree.StaffTreeMultiActivity
import com.eqdd.yiqidian.ui.tongxunlu.stafftree.StaffTreeSingleActivity
import com.eqdd.yiqidian.utils.ToastUtil
import com.jhj.datalibrary.tree.multi.BaseMultiTreeActivity
import com.lzy.okgo.OkGo
import com.lzy.okgo.model.Response
import kotlinx.android.synthetic.main.activity_recyclerview.*
import org.jetbrains.anko.startActivityForResult
import org.jetbrains.anko.toast
import java.text.SimpleDateFormat
import java.util.*

/**
 * Created by jhj on 18-5-31.
 */

class MeetingNoticeAddActivity : SlimBaseMultiEditActivity() {

    private var typeId: Int = -1
    private var infoBean: MeetingTypeInfoBean? = null
    private var type: String? = null

    private var person: ArrayList<DepartmentStaffTreeBean>? = arrayListOf()


    override fun initBinding() {
        clearData()
        setContentView(R.layout.activity_recyclerview)
        initTopTitleBar(View.VISIBLE, "会议类型")
        initTopRightText("新增", View.OnClickListener {
            val bean = slimAdapterEx.data
            OkGo.post<HttpResult<*>>(HttpConfig.BASE_URL + HttpConfig.MEETING_NOTICE_ADD)
                    .params("userGuid", user.guid)
                    .params("comid", user.companyId)
                    .params("settingId", typeId)
                    .params("type", bean[0].tag as? String)
                    .params("startTime", bean[3].content)
                    .params("endTime", bean[4].content)
                    .params("place", bean[5].content)
                    .params("attendees", bean[6].tag as? String)
                    .params("compere", bean[7].tag as? String)
                    .params("recorder", bean[8].tag as? String)
                    .params("aim", bean[9].content)
                    .execute(object : DialogCallBack<HttpResult<*>>(this) {
                        override fun onSuccess(response: Response<HttpResult<*>>) {
                            val httpResult = response.body()
                            ToastUtil.showShort(httpResult.msg)
                            if (httpResult.status == 200) {
                                setResult(Activity.RESULT_OK)
                                finish()
                            }
                        }
                    })
        })
    }

    override fun initRecyclerView(): RecyclerView {
        return recyclerView
    }


    override fun initData() {
        super.initData()
        typeId = intent.getIntExtra(Config.ID, -1)
        type = intent.getStringExtra(Config.TYPE)
        if (typeId == -1) {
            finish()
            toast("获取详情失败")
            return

        }
        OkGo.post<HttpResult<MeetingTypeInfoBean>>(HttpConfig.BASE_URL + HttpConfig.MEETING_TYPE_INFO)
                .params("companyId", user.companyId)
                .params("mettingId", typeId)
                .execute(object : DialogCallBack<HttpResult<MeetingTypeInfoBean>>(this@MeetingNoticeAddActivity) {
                    override fun onSuccess(response: Response<HttpResult<MeetingTypeInfoBean>>?) {
                        val result = response?.body()
                        if (result?.status == 200) {
                            infoBean = result.items
                            setEditBeans()
                        }
                    }
                })
    }


    override fun itemClick(p: Int) {
        when (slimAdapterEx.data[p].position) {
            3 -> {
                isUpper = true
                openTimePicker()
            }
            4 -> {
                isUpper = false
                openTimePicker()
            }
            6 -> {
                startActivityForResult<StaffTreeMultiActivity>(999, Config.TITLE to "参与人员", Config.ID to 0, Config.TYPE to StaffTreeMultiActivity.TYPE_CANYUREN, BaseMultiTreeActivity.SELECTED_DATA to person)
            }
            7 -> {
                startActivityForResult<StaffTreeSingleActivity>(1000, Config.TITLE to "主持人", Config.ID to 0, Config.TYPE to StaffTreeSingleActivity.TYPE_SINGLE_SELECT)
            }
            8 -> {
                startActivityForResult<StaffTreeSingleActivity>(1001, Config.TITLE to "记录人", Config.ID to 0, Config.TYPE to StaffTreeSingleActivity.TYPE_SINGLE_SELECT)
            }
        }
    }

    override fun setEditBeans() {
        infoBean?.let {

            val frequency = when {
                1 == it.frequency -> "每月"
                2 == it.frequency -> "每周"
                3 == it.frequency -> "每天"
                else -> "一次"
            }

            val builder = StringBuilder()
            val attendeesId = StringBuilder()
            it.attendees.forEach { att ->
                val bean = DepartmentStaffTreeBean()
                builder.append(att.username).append(",")
                attendeesId.append(att.userGuid).append(",")
                bean.id = att.userGuid
                bean.content = att.username
                bean.icon = att.headImage
                person?.add(bean)
            }


            val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);

            datas.add(SlimEditHintBean("会议类型", it.type, 0).setTag(it.type))
            datas.add(SlimEditHintBean("会议频率", frequency, 0).setTag(it.frequency))
            datas.add(SlimEditHintBean("会议时段", it.timeInterval, 0))
            datas.add(SlimTimeSelectBean("会议开始时间", sdf.format(parseData(it.startTime)?.time), 3, "请选择").setStartTime(true).setDeal(true).setNeed(true))
            datas.add(SlimTimeSelectBean("会议结束时间", sdf.format(parseData(it.endTime)?.time), 4, "选择择").setStartTime(false).setDeal(true).setNeed(true))
            datas.add(SlimEditEnterBean("会议地点", it.place, 5, "请输入").setNeed(true))
            datas.add(SlimEditEnterBean("参与人员", builder.substring(0, builder.length - 1), 6, "请选择").setDeal(true).setTag(attendeesId.substring(0, attendeesId.length - 1)).setNeed(true))
            datas.add(SlimEditEnterBean("主持人", it.compere.username, 7, "请选择").setDeal(true).setTag(it.compere.userGuid).setNeed(true))
            datas.add(SlimEditEnterBean("记录人", it.recorder.username, 8, "请选择").setDeal(true).setTag(it.recorder.userGuid).setNeed(true))
            datas.add(SlimEditEnterBean("会议目的", it.aim, 9, "请输入").setNeed(true))
            slimAdapterEx.register(R.layout.list_item_29, SlimInjector<SlimTimeSelectBean> { data, injector ->
                injector?.text(R.id.tv_left_content, data?.title)
                        ?.text(R.id.tv_right_content, data?.content)
                        ?.hint(R.id.tv_right_content, data?.hint)
            })
            slimAdapterEx.notifyDataSetChanged()
        }

    }

    private fun parseData(time: String?): Calendar? {
        if (time == null) {
            return null
        }
        val array = time.split(":")
        val calendar = Calendar.getInstance()
        calendar.set(Calendar.HOUR_OF_DAY, array[0].toInt())
        calendar.set(Calendar.MINUTE, array[1].toInt())
        return calendar

    }


    private var upDate: Date? = null
    private var downDate: Date? = null
    private var isUpper: Boolean = false
    private fun openTimePicker() {
        val sf = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA)
        val now = Calendar.getInstance()
        upDate = sf.parse(slimAdapterEx.getDataItem(3).content)
        downDate = sf.parse(slimAdapterEx.getDataItem(4).content)
        if (isUpper) {
            now.time = upDate
        } else {
            now.time = downDate
        }
        TimePickerView.Builder(this, TimePickerView.OnTimeSelectListener { date, v ->
            if (isUpper) {
                if (date.after(downDate)) {
                    toast("开始时间小于结束事件，请重新选择")
                    return@OnTimeSelectListener
                }
                upDate = date
                slimAdapterEx.getDataItem(3).content = sf.format(date)
                slimAdapterEx.notifyItemChanged(3)
            } else {
                if (date.before(upDate)) {
                    toast("开始时间小于结束事件，请重新选择")
                    return@OnTimeSelectListener
                }
                downDate = date
                slimAdapterEx.getDataItem(4).content = sf.format(date)
                slimAdapterEx.notifyItemChanged(4)
            }

        })
                .setOutSideCancelable(true)
                .setType(booleanArrayOf(true, true, true, true, true, false))
                .setDate(now)
                .build()
                .show()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (data == null)
            return
        if (resultCode == RESULT_OK) {
            when (requestCode) {

                999 -> {//参与人员
                    person = data.getSerializableExtra(BaseMultiTreeActivity.SELECTED_DATA) as ArrayList<DepartmentStaffTreeBean>
                    val id = StringBuilder()
                    val name = StringBuilder()
                    person?.forEach {
                        id.append(it.id).append(",")
                        name.append(it.name).append(",")
                    }
                    datas[6].content = name.substring(0, name.length - 1)
                    datas[6].tag = id.substring(0, id.length - 1)
                    slimAdapterEx.notifyItemChanged(6)
                }
                1000 -> {//主持人
                    val hostMan = data.getSerializableExtra("data") as DepartmentStaffTreeBean?
                    datas[7].content = hostMan?.name
                    datas[7].tag = hostMan?.id
                    slimAdapterEx.notifyItemChanged(7)

                }
                1001 -> {//记录人
                    val recordMan = data.getSerializableExtra("data") as DepartmentStaffTreeBean?
                    datas[8].content = recordMan?.name
                    datas[8].tag = recordMan?.id
                    slimAdapterEx.notifyItemChanged(8)
                }
            }
        }
    }

}
